package com.jd.org.service.impl;

import com.jd.basic.mapper.BaseMapper;
import com.jd.basic.query.BaseQuery;
import com.jd.basic.service.BaseService;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.AjaxResult;
import com.jd.basic.util.PageList;
import com.jd.org.domain.Department;
import com.jd.org.mapper.DepartmentMapper;
import com.jd.org.query.DepartmentQuery;
import com.jd.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
//类级别事务为读事务,分别在增删改的方法上面加写事务
//@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> tree() {
        ArrayList<Department> result = new ArrayList<>();
        List<Department> all = departmentMapper.findAll();
        System.err.println("部门集合" + all);
        Map<Long, Department> collect = all.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        for (Department department : all) {
            // 没有parentId则是顶级部门
            if (null == department.getParentId()){
                // 将顶级部门放入结果集中 用作树的顶点
                result.add(department);
            }else {
                // 进入else则表示增强for的当前变量有上级部门
                // 获取增强for当前对象的上级部门
                Department parent = collect.get(department.getParentId());
                System.err.println("子集" + parent);
                parent.getChildren().add(department);
            }
        }
        return result;
    }

}
